﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Data;
using RG.Common.Export;
using RG.Common.WPF.Controls.SortableGridView;

namespace RG.Common.WPF
{
    public class LambdaConverter : IValueConverter
    {
        public IColumnInfo Column { get; private set; }
        public LambdaConverter(IColumnInfo column)
        {
            Column = column;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Column.GetValueForGrid(value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    }

    public class LambdaMultiConverter : IMultiValueConverter
    {
        public IColumnInfo Column { get; private set; }
        public LambdaMultiConverter(IColumnInfo column)
        {
            Column = column;
        }

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            return Column.GetValueForGrid(values[0]);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            return new[] { value };
        }
    }


    [ValueConversion(typeof(IEnumerable<IColumnInfo>), typeof(ViewBase))]
    public class ColumnInfoToGridViewConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var view = new GridView();
            var columns = value as IEnumerable<IColumnInfo>;
            int i = 0;
            if (columns != null)
                foreach (var info in columns)
                {
                    var binding = new MultiBinding { Converter = new LambdaMultiConverter(info) };
                    binding.Bindings.Add(new Binding());
                    binding.Bindings.Add(new Binding(info.PropertyPath));
                    var temp = new SortableGridViewColumn
                                   {
                                       Width = info.Width,
                                       DisplayMemberBinding = binding,
                                       SortPropertyName = "c" + i++,
                                       Header = info.Header,
                                       ColumnInfo = info
                                   };

                    view.Columns.Add(temp);
                }
            return view;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    }
}
